package io.xccit.system.service.impl;

import io.xccit.model.system.SysUser;
import io.xccit.security.util.CustomUserDetail;
import io.xccit.system.service.ISysMenuService;
import io.xccit.system.service.ISysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author CH_ywx
 * @date 2023-06-27
 * @description 自定义获取用户信息Service
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getUserInfoByUserName(username);
        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if (sysUser.getStatus() == 0L){
            throw new RuntimeException("用户状态禁用");
        }
        //根据用户ID获取用户操作权限数据
        Long userId = sysUser.getId();
        List<String> userPermsList = sysMenuService.getUserButtonList(userId);
        //转换成security要求的格式
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        for (String perms : userPermsList) {
            authorityList.add(new SimpleGrantedAuthority(perms.trim()));
        }
        return new CustomUserDetail(sysUser, authorityList);
    }
}
